<template>
  <div class="container" style=" padding-bottom: 100px">
    <div class="filter-section">
      <div class="search-box">
        <el-input
          style="width: 240px; margin-right: 20px"
          placeholder="请输入剧名"
          v-model="name"
        ></el-input>
        <el-button type="primary" @click="loadFilePage">
          <i class="el-icon-search"></i> 搜索
        </el-button>
        <el-button type="warning" @click="reset">
          <i class="el-icon-refresh"></i> 重置
        </el-button>
      </div>

      <div class="filter-box">
        <el-select
          v-model="selectedClassify"
          placeholder="选择分类"
          clearable
          @change="handleFilter"
          style="width: 200px; margin-right: 20px"
        >
          <el-option
            v-for="item in classifyOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>

        <el-select
          v-model="selectedTags"
          placeholder="选择标签"
          clearable
          @change="handleFilter"
          style="width: 200px"
        >
          <el-option
            v-for="item in tagOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </div>
    </div>

    <div style="margin: 10px 0">
      <el-button
        style="margin-left: 5px"
        type="primary"
        @click="handleAdd"
        ><i class="el-icon-search"></i> 新增</el-button
      >

      <el-popconfirm
        class="ml-5"
        confirm-button-text="确定"
        cancel-button-text="我再想想"
        icon="el-icon-info"
        icon-color="red"
        title="您确定批量删除这些数据吗？"
        @confirm="delBatch"
      >
        <template v-slot:reference>
          <el-button type="danger"
            >批量删除 <i class="el-icon-remove-outline"></i
          ></el-button>
        </template>
      </el-popconfirm>
    </div>

    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="编号" width="80"></el-table-column>
      <el-table-column prop="name" label="剧名" width="120"></el-table-column>
      <el-table-column prop="title" label="标题" width="150"></el-table-column>
      <el-table-column prop="director" label="导演" width="120"></el-table-column>
      <el-table-column prop="actors" label="主演" width="120">
        <template v-slot="{ row }">
          <span>{{ truncateString(row.actors, 20) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="封面图" width="800">
        <template v-slot="scope">
          <div class="image-container">
            <div class="image-wrapper" @click="showBigImage(scope.row.imgone)">
              <el-image 
                class="preview-image"
                :src="scope.row.imgone"
                :preview-src-list="[]"
                fit="cover"
              />
            </div>
            <div class="image-wrapper" @click="showBigImage(scope.row.imgtwo)">
              <el-image 
                class="preview-image"
                :src="scope.row.imgtwo"
                :preview-src-list="[]"
                fit="cover"
              />
            </div>
            <div class="image-wrapper" @click="showBigImage(scope.row.imgthere)">
              <el-image 
                class="preview-image"
                :src="scope.row.imgthere"
                :preview-src-list="[]"
                fit="cover"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="classify" label="分类" width="100"></el-table-column>
      <el-table-column prop="tag" label="标签" width="200">
        <template v-slot="{ row }">
          <span>{{ truncateString(row.tag, 30) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="mark" label="评分" width="80"></el-table-column>
      <el-table-column prop="evaluate" label="评价" width="200">
        <template v-slot="{ row }">
          <span>{{ truncateString(row.evaluate, 30) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="source" label="来源" width="120">
        <template v-slot="scope">
          <el-link type="primary" :href="scope.row.source" target="_blank">豆瓣链接</el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template v-slot="scope">
          <el-button type="primary" @click="handEdit(scope.row)">编辑</el-button>
          <el-popconfirm
            title="确定删除吗？"
            @confirm="del(scope.row.id)"
          >
            <template v-slot:reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="form.id ? '修改信息' : '新增信息'"
      v-model="dialogVisible"
      width="50%"
    >
      <el-form label-width="120px" style="width: 85%; margin: 0 auto">
        <el-form-item label="剧名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="导演">
          <el-input v-model="form.director"></el-input>
        </el-form-item>
        <el-form-item label="主演">
          <el-input type="textarea" v-model="form.actors"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="form.classify"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-input type="textarea" v-model="form.tag"></el-input>
        </el-form-item>
        <el-form-item label="评分">
          <el-input v-model="form.mark"></el-input>
        </el-form-item>
        <el-form-item label="评价">
          <el-input type="textarea" v-model="form.evaluate"></el-input>
        </el-form-item>
        <el-form-item label="来源">
          <el-input v-model="form.source"></el-input>
        </el-form-item>
        <el-form-item label="封面图片1">
          <el-upload
            action="http://localhost:9090/api/file/cover"
            :data="{ name: form.name + '_1' }"
            :before-upload="beforeCoverUpload"
            @success="(res) => handleImgUploadSuccess(res, 'imgone')"
          >
            <el-button size="small" type="primary">上传图片1</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="封面图片2">
          <el-upload
            action="http://localhost:9090/api/file/cover"
            :data="{ name: form.name + '_2' }"
            :before-upload="beforeCoverUpload"
            @success="(res) => handleImgUploadSuccess(res, 'imgtwo')"
          >
            <el-button size="small" type="primary">上传图片2</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="封面图片3">
          <el-upload
            action="http://localhost:9090/api/file/cover"
            :data="{ name: form.name + '_3' }"
            :before-upload="beforeCoverUpload"
            @success="(res) => handleImgUploadSuccess(res, 'imgthere')"
          >
            <el-button size="small" type="primary">上传图片3</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">{{ form.id ? '修改' : '新增' }}</el-button>
        </div>
      </template>
    </el-dialog>

    <el-pagination
      style="justify-content: center; margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[2, 5, 10, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <el-dialog
      v-model="imagePreviewVisible"
      width="800px"
      :show-close="true"
      @close="closePreview"
      custom-class="image-preview-dialog"
    >
      <img :src="currentPreviewImage" class="big-preview-image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import request from "@/utils/request";
import { ElMessage } from "element-plus";
// import axios from "axios";
import { useRouter } from "vue-router";
const router=useRouter()
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(5);
const dialogVisible = ref(false);
const tableData = ref([]);
const multipleSelection = ref([]);
const NewCover=ref("");
const NewName=ref("")
const name=ref('');
const coverUpload = ref(null)
const form = ref({
  id: "",
  name: "",
  title: "",
  director: "",
  actors: "",
  classify: "",
  tag: "",
  mark: "",
  evaluate: "",
  source: "",
  imgone: "",
  imgtwo: "",
  imgthere: ""
});

// 添加预览相关的响应式变量
const imagePreviewVisible = ref(false)
const currentPreviewImage = ref('')

// 修改筛选相关的变量定义
const selectedClassify = ref('')
const selectedTags = ref('')
const classifyOptions = ref([])
const tagOptions = ref([])

// 添加获取分类和标签的方法
const fetchClassifyAndTags = async () => {
  try {
    // 获取分类列表
    const classifyRes = await request.get("/recommended/classifies");
    console.log('0----',classifyRes.data.data);
    
    if (classifyRes.data.code === '200') {
      classifyOptions.value = classifyRes.data.data || [];
      tagOptions.value = tagRes.data.data || [];
    }

    // 获取标签列表
    // const tagRes = await request.get("/recommended/tags");
    // if (tagRes.data.code === '200') {
    //   tagOptions.value = tagRes.data.data || [];
    // }
  } catch (error) {
    console.error("获取分类和标签失败:", error);
    ElMessage.error("获取筛选选项失败");
  }
}

onMounted(() => {
  loadFilePage();
  fetchClassifyAndTags(); // 页面加载时获取分类和标签
});
// const getUploadData = () => {
//   console.log(NewName.value,"====");
//   return {
//     name: NewName.value, // Dynamic value of name
//   };

// };

//字数限制
const truncateString = (str, maxLength) => {
  if (!str) return "";
  if (str.length <= maxLength) {
    return str;
  } else {
    return str.slice(0, maxLength) + "...";
  }
};

const save = async () => {
  try {
    let url = form.value.id ? '/recommended/update' : '/recommended/save';
    const res = await request.post(url, form.value);
    
    if (res.data.code === "200") {
      ElMessage.success(form.value.id ? "修改成功" : "添加成功");
      dialogVisible.value = false;
      loadFilePage();
    } else {
      ElMessage.error(form.value.id ? "修改失败" : "添加失败");
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("操作失败");
  }
};

const beforeCoverUpload = async () => {
  // 在上传新图片之前，先删除原有图片
  await deleteOldImage(); // 调用删除原有图片的方法
  // 继续上传新图片
  return true;
};

const deleteOldImage = async () => {
  try {
    // 假设你从后端获取了原有图片的URL
    const cover =NewCover.value
    console.log(cover,"===");
    // 发送请求删除原有图片
    await request.post('/file/coverOne', { params: { cover: cover } });
    console.log("原有图片删除成功");
 
  } catch (error) {
    console.error("原有图片删除失败", error);
  }
};
const handleImgUploadSuccess = (response, imageField) => {
  form.value[imageField] = response;
};

const del = async (detailsId) => {
  const res = await request.delete(`/recommended/${detailsId}`);
  if (res.data.code === "200") {
    ElMessage.success("删除成功");
    loadFilePage();
  } else {
    ElMessage.error("删除失败");
  }
};

const reset = () => {
  name.value = ''
  selectedClassify.value = ''
  selectedTags.value = ''
  loadFilePage()
};

const resetForm = () => {
  form.value = {
    id: "",
    name: "",
    title: "",
    director: "",
    actors: "",
    classify: "",
    tag: "",
    mark: "",
    evaluate: "",
    source: "",
    imgone: "",
    imgtwo: "",
    imgthere: ""
  }
  NewCover.value = ''
  NewName.value = ''
  // 清除上传组件的状态
  if (coverUpload.value) {
    coverUpload.value.clearFiles()
  }
}

const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

const loadFilePage = async () => {
  try {
    const res = await request.get("/recommended/paging", {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        name: name.value,
        classify: selectedClassify.value,
        tag: selectedTags.value
      },
    });
    
    tableData.value = res.data.data.records || [];
    total.value = res.data.data.total || 0;
  } catch (error) {
    if (error.response) {
    // 请求已发出，但服务器响应了状态码不在2xx范围内的内容
    console.error('服务器响应错误:', error.response.status, error.response.data);
    // 你可以根据状态码做不同的处理
    if (error.response.status === 402 || error.response.status === 405) {
      // 处理405错误
    localStorage.removeItem('token')
    localStorage.removeItem('userName')
    localStorage.removeItem('menus')
    localStorage.removeItem('userType')
    // 重定向到登录页面
    router.push('/login')
    }
  } else if (error.request) {
    // 请求已发出，但没有收到响应
    console.error('请求已发送，但未收到响应:', error.request);
  } else {
    // 其他错误（如配置错误导致请求未发送）
    console.error('错误:', error.message);
  }
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  loadFilePage();
};

const handleCurrentChange = (val) => {
  pageNum.value = val;
  loadFilePage();
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const delBatch = async () => {
  if (!multipleSelection.value.length) {
    ElMessage.error("请选择需要删除的数据");
    return;
  }

  const ids = multipleSelection.value.map((v) => v.id);
  try {
    const res = await request.post("/recommended/del/batch", ids);
    if (res.data.code === "200") {
      ElMessage.success("批量删除成功");
      loadFilePage();
    } else {
      ElMessage.error("批量删除失败");
    }
  } catch (error) {
    console.error("批量删除错误:", error);
    ElMessage.error("批量删除失败，请重试");
  }
};

const handEdit = (row) => {
  form.value = { ...row };
  dialogVisible.value = true;
};

// 添加预览相关的方法
const showBigImage = (imageUrl) => {
  currentPreviewImage.value = imageUrl
  imagePreviewVisible.value = true
}

const closePreview = () => {
  imagePreviewVisible.value = false
  currentPreviewImage.value = ''
}

// 处理筛选变化
const handleFilter = () => {
  pageNum.value = 1
  loadFilePage()
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.el-table {
  margin-top: 20px;
}

.image-container {
  display: flex;
  gap: 20px; /* 增加图片之间的间距 */
  padding: 10px;
}

.image-wrapper {
  cursor: pointer;
}

/* 大图预览样式 */
:deep(.image-preview-dialog) {
  background: rgba(0, 0, 0, 0.7);
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.big-preview-image {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
}

/* 修改原有的预览图片样式 */
.preview-image {
  width: 200px !important;
  height: 160px !important;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.preview-image:hover {
  transform: scale(1.05);
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.search-box {
  display: flex;
  align-items: center;
}

.filter-box {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 美化选择器样式 */
:deep(.el-select .el-input__wrapper) {
  background: white;
}

:deep(.el-select:hover .el-input__wrapper) {
  border-color: #409eff;
}
</style>
